package com.fingard.dsp.bank.directbank.ccblifeicbc02;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 今日明细及历史明细查询
 * 
 * 需求描述：
 * 		1、指令代码：QHISD -- 支持今日明细及历史明细查询
 * @author Cruise
 * @date 2018/10/23
 */
public class CCBLifeICBC02Transaction extends CCBLifeICBC02Base implements ITransaction {
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        
        String tmpRespCode = "";
        String tmpRespInfo = "";
        
        try {
            int qryCount = 0;
            String nextTag = "";
            while (tmpRespCode.length() == 0) {
                qryCount++;
                CCBLifeICBC02Header tmpBankHeader = new CCBLifeICBC02Header();
                tmpBankHeader.packageID = p_req7516.reqHeader.transSeqID + String.valueOf(qryCount);
                if (tmpBankHeader.packageID.length() > 35) {
                	tmpBankHeader.packageID = tmpBankHeader.packageID.substring(tmpBankHeader.packageID.length() - 35, tmpBankHeader.packageID.length());
                }
                tmpBankHeader.fSeqNo = tmpBankHeader.packageID;
                tmpBankHeader.transCode = "QHISD";
                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHeader(xmlWriter, tmpBankHeader);
                xmlWriter.writeElementString("AccNo", p_req7516.actNum);
                xmlWriter.writeElementString("BeginDate", p_req7516.dateFrom);
                xmlWriter.writeElementString("EndDate", p_req7516.dateTo);
                xmlWriter.writeElementString("MinAmt", "0");
                xmlWriter.writeElementString("MaxAmt", "99999999999999999");
                xmlWriter.writeElementClosed("BankType");
                xmlWriter.writeElementString("NextTag", nextTag, true);
                xmlWriter.writeElementClosed("CurrType");
                xmlWriter.writeElementClosed("DueBillNo");
                xmlWriter.writeElementClosed("AcctSeq");
                xmlWriter.writeElementClosed("ComplementFlag");
                xmlWriter.writeEndDocument();
                
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                
                XmlTextReader tmpBkReader;
                String tmpAccNo = "";
                String tmpCurrType = "";
                String tmpAtsCur = "";
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                        if (isActiveRetCode(tmpRetCode)) {
                            nextTag = tmpBkReader.getFirstText("/CMS/eb/out/NextTag");
                            tmpAccNo = tmpBkReader.getFirstText("/CMS/eb/out/AccNo");
                            tmpCurrType = tmpBkReader.getFirstText("/CMS/eb/out/CurrType");
                            tmpAtsCur = convertCurToATS(tmpCurrType);
                            if (!tmpAccNo.equals(p_req7516.actNum)) {
                                tmpRespCode = "-1";
                                tmpRespInfo = "银行返回的账号" + tmpAccNo + "与请求账号" + p_req7516.actNum + "不符";
                                break;
                            }
                            String tmpTotalNum = tmpBkReader.getFirstText("/CMS/eb/out/TotalNum");
                            if (StringHelper.isNullOrEmpty(tmpTotalNum)) {
                                tmpRespCode = "-1";
                                tmpRespInfo = "银行返回的交易条数为空";
                                break;
                            }
                        } else if (tmpRetCode.equals("B0116") && qryCount == 1) {
                            tmpRespCode = "0";
                            tmpRespInfo = tmpRetMsg;
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMsg;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
                
                while (tmpBkReader.read("/CMS/eb/out/rd")) {
                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                    tmpRetDetail.actNum = tmpAccNo;
                    tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("RecipAccNo");
                    tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("RecipName");
                    tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("RecipBkName");
                    if (StringHelper.isNullOrEmpty(tmpRetDetail.recAccBank)) {
                        tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("RecipBkNo");
                    }
                    String tmpDrcrf = tmpBkReader.readedXElement.getSingleText("Drcrf");
                    if (tmpDrcrf.trim().equals("1")) {
                        String tmpDebitAmount = tmpBkReader.readedXElement.getSingleText("DebitAmount").trim();
                        if (tmpDebitAmount.startsWith("-")) {
                            //借负，银行退票,表示收入。
                            tmpRetDetail.tranAmt = StringHelper.amountDivide100(tmpDebitAmount.substring(1));
                            tmpRetDetail.cdFlag = "2";//借贷表示至为贷，表示收入
                        } else {
                            //借正，正常业务
                            tmpRetDetail.tranAmt = StringHelper.amountDivide100(tmpDebitAmount);
                            tmpRetDetail.cdFlag = "1";
                        }
                    } else if (tmpDrcrf.trim().equals("2")) {
                        String tmpCreditAmount = tmpBkReader.readedXElement.getSingleText("CreditAmount").trim();
                        if (tmpCreditAmount.startsWith("-")) {
                            //贷负，目前应该没有这种业务，按照正常的程序逻辑做一下处理。
                            tmpRetDetail.tranAmt = StringHelper.amountDivide100(tmpCreditAmount.substring(1));
                            tmpRetDetail.cdFlag = "1";//借贷表示至为借，表示支出
                        } else {
                            //贷正，正常业务
                            tmpRetDetail.tranAmt = StringHelper.amountDivide100(tmpCreditAmount);
                            tmpRetDetail.cdFlag = "2";
                        }

                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "借贷标志Drcrf有误：" + tmpDrcrf;
                        break;
                    }
                    String tmpDate = tmpBkReader.readedXElement.getSingleText("Date");
                    if (tmpDate.length() == 8) {
                        tmpRetDetail.tranDate = tmpDate.substring(0, 4) + "-" + tmpDate.substring(4, 6) + "-" + tmpDate.substring(6, 8);
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "交易日期Date格式有误：" + tmpDate;
                        break;
                    }
                    //<Time>2012-09-10-00.45.34.597322</Time>
                    String tmpTime = tmpBkReader.readedXElement.getSingleText("Time");
                    tmpRetDetail.postTimestamp = tmpTime;
                    if (tmpTime.length() > 18) {
                        tmpRetDetail.tranTime = tmpTime.substring(0, 10) + " " + tmpTime.substring(11, 19).replace('.', ':');
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "时间戳Time格式有误：" + tmpTime;
                        break;
                    }
                    tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                    if (!StringHelper.isNullOrEmpty(tmpBkReader.readedXElement.getSingleText("Balance"))) {
                        tmpRetDetail.accBal = StringHelper.amountDivide100(tmpBkReader.readedXElement.getSingleText("Balance"));
                    }

                    tmpRetDetail.billNum = tmpBkReader.readedXElement.getSingleText("VouhNo");
                    tmpRetDetail.billType = tmpBkReader.readedXElement.getSingleText("VouhType");
                    if (StringHelper.isNullOrEmpty(tmpRetDetail.billType)) {
                        tmpRetDetail.billType = tmpBkReader.readedXElement.getSingleText("BusType");
                    }

                    tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("Summary");
                    tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("UseCN");
                    tmpRetDetail.abstr = pickupAbstr(tmpBkReader.readedXElement.getSingleText("PostScript"), tmpBkReader.readedXElement.getSingleText("Summary"), tmpBkReader.readedXElement.getSingleText("UseCN"));

                    tmpRetDetail.cur = tmpAtsCur;

                    tmpRetDetail.seqId = tmpBkReader.readedXElement.getSingleText("RepReserved3");
                    tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("VouhNo");

                    tmpRetDetail.payCode = tmpBkReader.readedXElement.getSingleText("PostScript");
                    if (!getBankConfig().getValueAsBool("qryTransPayCodeOnlyPostscript")) {
                        if (StringHelper.isNullOrEmpty(tmpRetDetail.payCode)) {
                            tmpRetDetail.payCode = tmpBkReader.readedXElement.getSingleText("Ref");
                        }
                        if (StringHelper.isNullOrEmpty(tmpRetDetail.payCode)) {
                            tmpRetDetail.payCode = tmpBkReader.readedXElement.getSingleText("Oref");
                        }
                        if (StringHelper.isNullOrEmpty(tmpRetDetail.payCode)) {
                            tmpRetDetail.payCode = tmpBkReader.readedXElement.getSingleText("RepReserved4");
                        }
                    }
                    nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());
                    retAts.writeRetDetail(tmpRetDetail);
                    if ("receiptXml".equals(getBankConfig().getValueAsString("receiptType"))) {
                        generateHisTranFile(tmpRetDetail, tmpBkReader.readedXElement.getSingleText("RepReserved4"));
                    }
                }
                if (StringHelper.isNullOrEmpty(nextTag)) {
                    break;
                }
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return null;
    }

    private void generateHisTranFile(RetAtsTransDetail tmpRetDetail, String askNumber) throws Exception {
        FileOutputStream fos = null;
        try {
            String tmpByDate = Format.Date8Format.format(Format.Date10Format.parse(tmpRetDetail.tranDate));
            tmpByDate = tmpByDate.substring(0, 6) + File.separator + tmpByDate.substring(6, 8);
            String filePath = getBankConfig().getValueAsString("hisTranFile");
            if (StringHelper.isNullOrEmpty(filePath)) {
                filePath = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "tempfile" + File.separator + "hisTranFile" + File.separator;
            }
            filePath = filePath + tmpByDate + File.separator + reqHeader.bankCode + File.separator + tmpRetDetail.actNum + ".txt";
            File batFile = new File(filePath);
            if (!batFile.getParentFile().exists()) {
                batFile.getParentFile().mkdirs();
            }
            String fileContent = "";
            String newFileContent = tmpRetDetail.actNum + "|" + tmpRetDetail.tranDate + "|" + askNumber + "|" + tmpRetDetail.seqId;
            if (!batFile.exists()) {
                batFile.createNewFile();
            } else {
                fileContent = FtpUtil.getTextFromFile(filePath, getCharset());
                if (fileContent.contains(newFileContent)) {
                    return;
                }
            }
            fos = new FileOutputStream(batFile);
            fos.write(fileContent.concat(newFileContent).getBytes());
        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
}
